﻿// ***************************************************************
//  FieldColumn.cs   version:  0.4.0   date: 11/13/2007-2008
//  -------------------------------------------------------------
//  
//  -------------------------------------------------------------
//  Copyright (C) Midapex Software 2003-2007-2008 - All Rights Reserved
// ***************************************************************
// 
// ***************************************************************
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Data;
using Midapex.SmartOrm.Properties;
namespace Midapex.SmartOrm
{
    public class FieldColumn:Column
    {
        FieldInfo field;

        private FieldColumn()
        {
        }

        public FieldColumn(ColumnAttribute colAttr, FieldInfo field)
            :base(colAttr)
        {
            if(field==null)
            {
                throw new ArgumentNullException();
            }

            this.field = field;
            if (colAttr.Name == null || colAttr.Name == string.Empty)
                name = field.Name;
            else
                name = colAttr.Name;

            name = name.ToUpper();

            if (colAttr.DbType == DbType.Object)
            {
                //设置数据类型
                this.DbType = BuildDbType(field.FieldType);
            }

            //不能在基本数据列中声明基础数据类型，否则不能判断数据列的数据类型
            if(this.DataType == typeof(object))
            {
                throw new OrmLogicException(Resource.ExDeclareObjectTypeNotAllowed);
            }
        }

        public override object Read(object target)
        {
            return field.GetValue(target);
        }
        public override void Write(object target, object colValue)
        {
            field.SetValue(target, colValue);
        }

        public override Type DataType
        {
            get
            {
                return field.FieldType;
            }
        }

        public override object Clone()
        {
            FieldColumn col = new FieldColumn();
            Copy(col, this);
            col.field = this.field;
            return col;
        }

    }
}
